/**
 * 
 */
package com.bible.fire.local;

import java.io.File;
import java.util.HashMap;
import java.util.Map;


import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.MKGeneralListener;
import com.baidu.mapapi.map.MKEvent;
import com.bible.fire.service.BDLocationService;
import com.bible.fire.util.AndroidUtil;
import com.bible.fire.util.SystemConstant;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

/**
 * @author zhangyp
 *
 */
public class AppContext extends Application {
	
	private static Application gContext;
	private static AppContext instance;
	public static boolean m_bKeyRight = true;
    public BMapManager mBMapManager = null;
	
	//存储一些全局的变量和值
	private static Map<String, Object> appMap;
	
	@Override
	public void onCreate(){
		super.onCreate();
		//gContext = getApplicationContext();
		gContext = this;
		instance = this;
		appMap = new HashMap<String, Object>();
		setAttribute( "app", "Night Of Fire" );
		CrashHandler.getInstance().init( gContext );
		ConfigManager.initAppConfig( gContext );
		initBaiduMapManager(this);
		startGlobalServices();
		initSystemVars();
		initSystemFolder();
	}
	
	public static AppContext getInstance(){
		return instance;
	}
	
	public static Context getContext(){
		return gContext;
	}
	
	@Override
	public void onTerminate(){
		if (mBMapManager != null) {
            mBMapManager.destroy();
            mBMapManager = null;
        }
		super.onTerminate();
	}
	
	public void startGlobalServices(){
		Intent bdLocIntent = new Intent(this, BDLocationService.class );
		this.startService( bdLocIntent );
	}
	
	private void initSystemVars(){
		String imsi = AndroidUtil.getIMSI();
		if( imsi != null && imsi.length() > 0 ){
			setAttribute( "imsi", imsi );
		}
		String deviceId = AndroidUtil.getDeviceId();
		if( deviceId != null && deviceId.length() > 0 ){
			setAttribute( "device_id", deviceId );
		}
	}
	
	private void initSystemFolder(){
		if( AndroidUtil.isHasSdcard() ){
			try{
				File file = new File( SystemConstant.IMG_PATH_IN_SDCARD );
				if(!file.exists()){
					file.mkdirs();
				}
				file = new File( SystemConstant.FILE_DOWNLOAD_PATH );
				if(!file.exists()){
					file.mkdirs();
				}
				file = new File( SystemConstant.TWO_DIMENSION_CODE_PATH );
				if(!file.exists()){
					file.mkdirs();
				}
				file = new File( SystemConstant.FILE_UPLOAD_PATH );
				if(!file.exists()){
					file.mkdirs();
				}
			}catch(Exception e) {
				Log.e("AppContext", "init folder", e);
			}			
		}
	}
	
	public void initBaiduMapManager(Context context) {
        if (mBMapManager == null) {
            mBMapManager = new BMapManager(context);
        }

        if (!mBMapManager.init(SystemConstant.API_KEY_MAP_BAIDU,new BaiduMapListener())) {
            Toast.makeText(gContext, "BMapManager  初始化错误!", Toast.LENGTH_LONG).show();
        }
	}
	
	// 常用事件监听，用来处理通常的网络错误，授权验证错误等
    public static class BaiduMapListener implements MKGeneralListener {
        
        @Override
        public void onGetNetworkState(int iError) {
            if (iError == MKEvent.ERROR_NETWORK_CONNECT) {
            	//离线情况下经常报错,给用户造成困扰
                //Toast.makeText(gContext, "您的网络出错啦！",Toast.LENGTH_LONG).show();
            	Log.d("baidu map init", "网络出错");
            }
            else if (iError == MKEvent.ERROR_NETWORK_DATA) {
                Toast.makeText(gContext, "输入正确的检索条件！",Toast.LENGTH_LONG).show();
            }
            // ...
        }

        @Override
        public void onGetPermissionState(int iError) {
            if (iError ==  MKEvent.ERROR_PERMISSION_DENIED) {
                //授权Key错误：
                Toast.makeText(gContext, "请输入正确的百度地图授权Key！", Toast.LENGTH_LONG).show();
                AppContext.m_bKeyRight = false;
            }
        }
    }
	
	public boolean setAttribute( String key, Object value){
		if( key != null ){
		    appMap.put(key, value);
		}
		return true;
	}
	
	public Object getAttribute( String key ){
		if( key != null ){
		    return appMap.get( key );
		}else{
			return null;
		}
	}
	
	public boolean removeAttribute( String key ){
		if( key != null && appMap.containsKey(key) ){
		   appMap.remove(key);
		}
		return true;
	}
	
	public boolean clearAttribute(){
		appMap.clear();
		return true;
	}

}
